export default {
	namespaced: true,
	
	state: () => ({
		
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart:  JSON.parse(uni.getStorageSync('cart') || '[]'),
		swich: false,
	}),
	
	mutations: {
		
		addToCart(state, goods){
			// 索引内部cart是否存在
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult) {
				findResult.goods_count++
			}else {
				state.cart.push(goods)
			}
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		
		// 更新单个状态
		updateGoodsState(state, goods){
			const findRes = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findRes) {
				findRes.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		// 更改物品数量
		updateGoodsNumber(state, goods){
			const findRes = state.cart.find(x => x.goods_id === goods.goods_id)
				
			if(findRes) {
				findRes.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		// 勾选全选
		updataAllGoodsState(state, newState) {
			state.cart.forEach(x => x.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
		// 删除物品
		removeGoodsById(state, goods_id){
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			this.commit('m_cart/saveToStorage')
		}
		
	},
	
	getters: {
		
		//商品中所有数量
		total(state) {
		      // let c = 0
		      // state.cart.forEach(goods => c += goods.goods_count)
		      // return c
			  
			  return state.cart.reduce((total, item) => total += item.goods_count,0)
		   },
		// 商品中所有已勾选的总数量
		checkedCount(state) {
			//过滤选中状态，cart 对象，
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 总金额
		checkedGoodsAmount(state){
			return state.cart.filter(x => x.goods_state)
			.reduce((total, item) => total += item.goods_price * item.goods_count,0)
			.toFixed(2)
		}
	}
}